import { users, verificationCodes } from '../../../server/database/schema';
import { hashPassword } from '../../../server/utils/auth';
import {gt} from 'drizzle-orm'

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email, code, password } = body;

  const db = useDrizzle()

  // 验证验证码
  const verification = await db.select()
    .from(verificationCodes)
    .where(
      and(
        eq(verificationCodes.email, email),
        eq(verificationCodes.code, code),
        eq(verificationCodes.type, 'register'),
        gt(verificationCodes.expiresAt, new Date())
      )
    )
    .limit(1);

  if (!verification.length || verification[0].used) {
    throw createError({ statusCode: 400, message: 'Invalid verification code' });
  }

  // 标记验证码已使用
  await db.update(verificationCodes)
    .set({ used: true })
    .where(eq(verificationCodes.id, verification[0].id));

  // 创建用户
  const passwordHash = await hashPassword(password);
  await db.insert(users).values({
    email,
    passwordHash,
    nickname: email.split('@')[0], // 默认用户名
    emailVerified: true
  });

  return { success: true };
});

